package com.xbongbong.saas.script.service.impl;

import com.alibaba.dingtalk.openapi.exception.OApiException;
import com.alibaba.dingtalk.openapi.utils.HttpHelper;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.util.FineClueUtil;
import com.xbongbong.paas.model.FineClueCompanyModel;
import com.xbongbong.paas.model.FineClueUserModel;
import com.xbongbong.paas.model.SearchCustomerCompanyModel;
import com.xbongbong.paas.pojo.dto.MigrateSoukeDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.FineClueUrlConstant;
import com.xbongbong.pro.domain.entity.FineClueCompanyEntity;
import com.xbongbong.pro.domain.entity.FineClueUserEntity;
import com.xbongbong.pro.domain.entity.SearchCustomerCompanyEntity;
import com.xbongbong.pro.enums.SoukeMealEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.FineClueComboEnum;
import com.xbongbong.pro.script.pojo.vo.ScriptVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.script.service.MigrateSoukeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author: hongxiao
 * @date: 2021-12-30 10:38
 */
@Service("migrateSoukeServiceImpl")
public class MigrateSoukeServiceImpl implements MigrateSoukeService {
    private static final Logger LOG = LoggerFactory.getLogger(MigrateSoukeServiceImpl.class);
    @Resource
    private SearchCustomerCompanyModel searchCustomerCompanyModel;
    @Resource
    private FineClueUserModel fineClueUserModel;
    @Resource
    private FineClueCompanyModel fineClueCompanyModel;
    @Resource
    private ProBaseConfig proBaseConfig;

    @Override
    public ScriptVO migrateSouke(MigrateSoukeDTO migrateSoukeDTO) throws XbbException {
        ScriptVO scriptVO = new ScriptVO();
        long start = DateTimeUtil.getInt();
        List<String> corpidList = migrateSoukeDTO.getCorpidList();

        // 默认为工商查询
        SoukeMealEnum soukeMealEnum = migrateSoukeDTO.getAlias() != null && migrateSoukeDTO.getAlias().equals(SoukeMealEnum.SOUKE.getAlias()) ? SoukeMealEnum.SOUKE : SoukeMealEnum.BUSINESS;
        // 精线索类型：默认工商查询
        FineClueComboEnum fineClueComboEnum = Objects.equals(soukeMealEnum,SoukeMealEnum.SOUKE) ? FineClueComboEnum.FINE_CLUE : FineClueComboEnum.COMPANY_QUERY;

        if (CollectionsUtil.isEmpty(corpidList)) {
            // 查询搜客公司
            corpidList = searchCustomerCompanyModel.getCorpidListWithType(soukeMealEnum.getType());
        }
        Integer index = 1;
        Integer updateCount = 0;
        for (String corpid : corpidList) {
            LOG.warn("当前执行公司：" + corpid);
            LOG.warn(index + "/" + corpidList.size());
            index++;

            SearchCustomerCompanyEntity soukeCompanyEntity = searchCustomerCompanyModel.getByCorpid(corpid, soukeMealEnum.getType());
            if (soukeCompanyEntity == null || soukeCompanyEntity.getExtraExpiry() <= DateTimeUtil.getInt()) {
                continue;
            }

            String companyName = soukeCompanyEntity.getCompanyName();
            // 打通账号
            FineClueUserEntity fineClueUserEntity = fineClueUserModel.getSingleUserByCorpid(corpid);
            if (Objects.isNull(fineClueUserEntity)) {
                //账号打通
                String uid = UUID.randomUUID().toString();
                String content = corpid + ":" + uid;
                JSONObject object = new JSONObject();
                String resultContent = FineClueUtil.AESUrlSafeEncrypt(content, proBaseConfig.getFineClueKey(), "ECB");
                object.put("userName", companyName);
                object.put("companyName", companyName);
                object.put("content", resultContent);
                object.put("monthlyLeads", -1);
                String url = proBaseConfig.getFineClueUrl() + FineClueUrlConstant.REGISTER_URL;

                JSONObject post = null;
                try {
                    post = HttpHelper.httpPostDingtalk(url, object);
                } catch (OApiException e) {
                    LOG.error("调用精线索接口失败fineClue参数:{},url:{}", object.toString(), url);
                }
                if (post == null || !post.containsKey("errcode") || post.getInteger("errcode") != 200) {
                    LOG.error("调用精线索接口失败fineClue参数:{},url:{}", object.toString(), url);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                JSONObject data = post.getJSONObject(StringConstant.JSON_DATA);
                if (data == null || (!data.containsKey("account") && !data.containsKey("password"))) {
                    LOG.error("调用精线索接口失败data:{}", data);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                String account = data.getString("account");
                String password = data.getString("password");

                fineClueUserEntity = new FineClueUserEntity();
                fineClueUserEntity.setUuid(uid);
                fineClueUserEntity.setCorpid(corpid);
                fineClueUserEntity.setRegisterCorpid(corpid);
                fineClueUserEntity.setClueUserId(account);
                fineClueUserEntity.setClueUserPassword(password);
                fineClueUserEntity.setUserId(soukeCompanyEntity.getUserId());
                fineClueUserEntity.setClueUseNum(200);
                fineClueUserEntity.setClueUseType(1);
                fineClueUserEntity.setStaff(BasicConstant.ONE);

                try {
                    fineClueUserModel.insert(fineClueUserEntity);
                } catch (XbbException e) {
                    LOG.error("保存精线索账号失败：account{},password{}", account, password);
                    LOG.error("保存精线索账号失败", e);
                }
            }
            FineClueCompanyEntity clueCompanyEntity = fineClueCompanyModel.getByCorpid(corpid, fineClueComboEnum.getCode());
            if (clueCompanyEntity == null) {
                Integer useCount = Objects.equals(fineClueComboEnum ,FineClueComboEnum.FINE_CLUE) ? 150 : 0;
                clueCompanyEntity = new FineClueCompanyEntity();
                clueCompanyEntity.setCorpid(corpid);
                clueCompanyEntity.setUserId(soukeCompanyEntity.getUserId());
                clueCompanyEntity.setRegisterCorpid(corpid);
                clueCompanyEntity.setType(fineClueComboEnum.getCode());
                clueCompanyEntity.setCompanyName(companyName);
                clueCompanyEntity.setUsername(companyName);
                clueCompanyEntity.setUseCount(useCount);
                // todo 搜客需要设置注册人数
            }

            clueCompanyEntity.setExtraExpiry(soukeCompanyEntity.getExtraExpiry());

            try {
                fineClueCompanyModel.save(clueCompanyEntity);
            } catch (XbbException e) {
                LOG.error("保存精线索公司失败", e);
            }

            // todo 搜客迁移时处理账号问题
            if (Objects.equals(fineClueComboEnum, FineClueComboEnum.FINE_CLUE)) {

            }

            updateCount++;

        }

        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        scriptVO.setMsg("总共更新" + updateCount + "家公司");
        return scriptVO;
    }
}
